<?php
/**
 * Created by PhpStorm.
 * User: 
 * Date: 
 * Time: 
 */

namespace app\services\model;

use think\Config;
use think\Model;
use think\Db;

class Notice extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'notice';
    /**
     * [addOne description]
     * @param [type] $userId  [description]
     * @param [type] $title   [description]
     * @param [type] $content [description]
     */
    public function addOne($userId,$title,$content){
        $new['user_id'] = $userId;
        $new['title'] = $title;
        $new['content'] = $content;
        $ob = Db::table("notice");
        $ob->insert($new);
        return 0;
    }
    /**
     * [unReadNoticeCount description]
     * @param  [type] $userId [description]
     * @return [type]         [description]
     */
    public function unReadNoticeCount($userId,$status=0){
        $ob = Db::table("notice")
            ->where("user_id",$userId)
            ->where("status",$status);
        $info =$ob
            ->field([
                "count(id) as totalCount"
            ])->find();
        return $info['totalCount'];
    }

        /**
     * [noticeList description]
     * @param  [type] $userId  [description]
     * @param  [type] $reqData [description]
     * @return [type]          [description]
     */
    public function noticeList($userId,$reqData){
        $object = Db::table("notice")
            ->where("user_id",$userId);
            
        if(isset($reqData['status']) && $reqData['status']!=''){
            $object = $object->where("status",$reqData['status']);
        } 

        if(isset($reqData['page'])&&$reqData['page']){
            $page = $reqData['page'];
        }
        else{
            $page = 1;
        }
        $info = $object
            ->field([
                "id",
                "title",
                "content",
                "status",
                "create_time as createTime",
            ])
            ->order("id desc")
            ->paginate($reqData['pageSize'], false, ['page '=>$page]);
            // echo $object->getLastSql();exit;
        //修改当前页，消息为已读
        $unReadNoticeStr = '-1';
        foreach ($info as $key => $value) {
            if($value['status']==0){
                $unReadNoticeStr .= ',' .$value['id'];
            }
        }
        if($unReadNoticeStr!='-1'){
            //修改状态
            Db::table("notice")
                ->whereIn("id",$unReadNoticeStr)
                ->update([
                    "status"=>1
                ]);
        }
        
        return $info;
    }  
}